<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>学生课程成绩管理</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="css/style.css">

    <style>
        .modal-dialog-centered {
            display: flex !important;
            align-items: center;
            justify-content: center;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            overflow: auto;
            min-height: calc(100% - 1rem);
        }
    </style>
</head>
<body class="p-4">
<h2 class="mb-4">学生课程成绩管理</h2>

<div class="mb-3 d-flex gap-2">
    <input type="text" id="search" placeholder="搜索学生号或课程号" class="form-control w-50">
    <button class="btn btn-info" onclick="search()">搜索</button>
    <button class="btn btn-success" onclick="showAddModal()">新增</button>
</div>

<table class="table table-bordered table-hover shadow">
    <thead>
    <tr>
        <th>ID</th><th>学生号</th><th>课程号</th><th>成绩</th><th>操作</th>
    </tr>
    </thead>
    <tbody id="data-body"></tbody>
</table>


<!-- 分页导航 -->
<div class="d-flex justify-content-between align-items-center">
    <div>
        共 <span id="total-items">0</span> 条记录
    </div>
    <ul class="pagination mb-0">
        <li class="page-item" id="prev-page">
            <a class="page-link" href="#" onclick="prevPage()">上一页</a>
        </li>
        <li class="page-item">
            <span class="page-link" id="current-page">1</span>
        </li>
        <li class="page-item" id="next-page">
            <a class="page-link" href="#" onclick="nextPage()">下一页</a>
        </li>
        <li class="page-item">
            <select class="form-select form-select-sm" id="page-size" onchange="changePageSize()">
                <option value="5">5条/页</option>
                <option value="10" selected>10条/页</option>
                <option value="20">20条/页</option>
                <option value="50">50条/页</option>
            </select>
        </li>
    </ul>
</div>


<!-- 新增模态框 -->
<div class="modal fade" id="addModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">新增学生课程</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input id="newStudentNo" class="form-control mb-2" placeholder="学生号">
                <input id="newCourseNo" class="form-control mb-2" placeholder="课程号">
                <input id="newGrade" class="form-control mb-2" placeholder="成绩">
            </div>
            <div class="modal-footer">
                <button class="btn btn-success" onclick="addEntry()">保存</button>
                <button class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>

    // 分页状态
    let currentPage = 1;
    let totalPages = 1;
    let totalItems = 0;
    let pageSize = 10;
    let currentSearch = '';

    // 在页面加载完成后绑定事件
    $(document).ready(function() {
        // 监听搜索输入框的回车键
        $('#search').keydown(function(event) {
            if (event.key === 'Enter' || event.keyCode === 13) {
                search(); // 调用搜索函数
            }
        });
        loadData();
    });

    // 分页控制函数
    function prevPage() {
        if (currentPage > 1) {
            currentPage--;
            loadData(currentSearch);
        }
    }

    function nextPage() {
        if (currentPage < totalPages) {
            currentPage++;
            loadData(currentSearch);
        }
    }

    function changePageSize() {
        pageSize = parseInt($('#page-size').val());
        currentPage = 1;  // 改变每页条数时重置到第一页
        loadData(currentSearch);
    }

    // 确保 loadData 函数正确处理查询参数
    function loadData(query = '') {
        // 编码查询参数以防止特殊字符问题
        const encodedQuery = encodeURIComponent(query);
        $.get(`/studentCourse/list?search=${encodedQuery}&current=${currentPage}&size=${pageSize}`, function(data) {
            // 更新分页信息
            currentPage = data.current;
            totalPages = data.pages;
            totalItems = data.total;
            updatePaginationUI();

            // 渲染表格数据
            const rows = data.records.map(item => `
            <tr>
                <td>${item.id}</td>
                <td><input value="${item.studentNo}" data-id="${item.id}" class="form-control studentNo" disabled /></td>
                <td><input value="${item.courseNo}" data-id="${item.id}" class="form-control courseNo" disabled /></td>
                <td><input value="${item.grade}" data-id="${item.id}" class="form-control grade" disabled /></td>
                <td>
                    <button class="btn btn-primary btn-sm" onclick="toggleEdit(${item.id}, this)">编辑</button>
                    <button class="btn btn-danger btn-sm" onclick="remove(${item.id})">删除</button>
                </td>
            </tr>
        `).join('');
            $('#data-body').html(rows);
        }).fail(function(jqXHR, textStatus, errorThrown) {
            console.error("请求失败:", textStatus, errorThrown);
            alert("搜索失败，请检查控制台获取详细信息");
        });
    }

    function updatePaginationUI() {
        $('#current-page').text(currentPage);
        $('#total-items').text(totalItems);
        $('#prev-page').toggleClass('disabled', currentPage <= 1);
        $('#next-page').toggleClass('disabled', currentPage >= totalPages);
    }

    function search() {
        currentPage = 1;  // 搜索时重置到第一页
        currentSearch = $('#search').val().trim();  // 获取并修剪搜索值
        loadData(currentSearch);  // 传递搜索条件
    }

    function toggleEdit(id, btn) {
        const isEditing = $(btn).text() === '保存';
        const studentNoInput = $(`.studentNo[data-id=${id}]`);
        const courseNoInput = $(`.courseNo[data-id=${id}]`);
        const gradeInput = $(`.grade[data-id=${id}]`);

        if (isEditing) {
            const studentNo = studentNoInput.val();
            const courseNo = courseNoInput.val();
            const grade = gradeInput.val();

            $.ajax({
                url: '/studentCourse/update',
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify({ id, studentNo, courseNo, grade }),
                success: () => {
                    studentNoInput.prop('disabled', true);
                    courseNoInput.prop('disabled', true);
                    gradeInput.prop('disabled', true);
                    loadData(currentSearch);
                    $(btn).text('编辑');
                }
            });
        } else {
            studentNoInput.prop('disabled', false);
            courseNoInput.prop('disabled', false);
            gradeInput.prop('disabled', false);
            $(btn).text('保存');
        }
    }

    function remove(id) {
        $.ajax({
            url: `/studentCourse/delete/${id}`,
            type: 'DELETE',
            success: () => loadData(currentSearch)
        });
    }

    function showAddModal() {
        const modal = new bootstrap.Modal(document.getElementById('addModal'));
        $('#newStudentNo').val('');
        $('#newCourseNo').val('');
        $('#newGrade').val('');
        modal.show();
    }

    function addEntry() {
        const studentNo = $('#newStudentNo').val();
        const courseNo = $('#newCourseNo').val();
        const grade = $('#newGrade').val();
        $.ajax({
            url: '/studentCourse/add',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ studentNo, courseNo, grade }),
            success: () => {
                bootstrap.Modal.getInstance(document.getElementById('addModal')).hide();
                loadData(currentSearch);
            }
        });
    }

    loadData();
</script>
</body>
</html>